﻿<%@ Page Language="C#" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
	<head id="Head1" runat="server">
		<title>Processing Status</title>
		<link rel="shortcut icon" href="../../images/favicon.ico" />
	</head>
	<body>
		<form id="form1" runat="server">
			&nbsp;
			<asp:Literal ID="output" runat="server" Text="Error!" />
		</form>
	</body>

<script runat="server" id="PageLoad">

	protected void Page_Load(object sender, EventArgs e)
	{
		//TODO: test caller (trace?) ; write in DB to check whether it really does execute twice, or it's a mere visual bug.
		Response.Clear();
		Response.Write(htmlHeader);

		try
		{
			//TestResponseFlush();
			string sql = GetSqlFromQueryString();
			Response.Write(sql);
			if (sql.Length == 0)
			{
				Response.Write("<br/> Unknown value for the action parameter: '" + Request.QueryString["action"] + "'! " + System.Environment.NewLine);
			}
			else
				ProcessRequests(sql);
		}
		catch (Exception ex)
		{
			Response.Write("<br/> Uncaught Error!!! " + ex.ToString() + System.Environment.NewLine);
		}

		Response.Write(htmlFooter);
		Response.Flush();
		Response.Close();
	}
	
	private string htmlHeader = @"<html xmlns=""http://www.w3.org/1999/xhtml"">
				<head>
					<title>Processing Status</title>
					<link rel=""shortcut icon"" href=""../../images/favicon.ico"" />					
				</head>
			<body>";
	private string htmlFooter = @"
			</body>
		</html>";
</script>
<script runat="server" id="GetSqlFromQueryString">
	private string procedureName = "";
	private string labDomain = "";
	protected string GetSqlFromQueryString()
	{
		string action = Request.QueryString["action"];
		switch (action)
		{
			case "Valid":
				procedureName = "LabRequest_Expose";
				break;
			case "Inch":
			case "Close":
				procedureName = "LabRequest_Close";
				break;
			default:
				return "";
		}
		string idList = Request.QueryString["IDS"]; //strIDS
		if (!string.IsNullOrEmpty(idList))
		{
			idList = idList.Replace(".", ",").Replace(";", ",").Replace(":", "-");
			string[] groups = idList.Split(',');
			string condition = ""; int dummy;
			foreach (string id in groups)
				if (int.TryParse(id, out dummy))
					condition += " RequestID=" + id + " OR ";
				else if (id.Contains("-"))
				{
					string[] parts = id.Split('-');
					//NB: could check for (and handle) the case when parts[0] > parts[1]... B-)
					condition += " (RequestID>=" + parts[0] + " AND RequestID<=" + parts[1] + ") OR ";
				}
				//else, ignore it.
			idList = condition;
		}
		string startDate = Request.QueryString["SD"]; //strSD
		if (string.IsNullOrEmpty(startDate))
			startDate = "19000101 00:00";
		else
		{
			/*/
			tmpSD = split(strSD, "/")
			strBegin = tmpSD(2)
			strBegin = strBegin & Right("0" & tmpSD(1), 2)
			strBegin = strBegin & Right("0" & tmpSD(0), 2)
			strBegin = strBegin & " " & strST
			//*/
		}
		string endDate = Request.QueryString["ED"]; //strED
		if (string.IsNullOrEmpty(endDate))
			endDate = DateTime.Now.ToString("yyyyMMdd") + " 11:59"; //NB: why not 2359?
		else
		{
			/*/
			tmpED = split(strED, "/")
			strEnd = tmpED(2)
			strEnd = strEnd & Right("0" & tmpED(1), 2)
			strEnd = strEnd & Right("0" & tmpED(0), 2)
			strEnd = strEnd & " " & strET
			//*/
		}
		string section = Request.QueryString["Section"]; //strSection
		string medic = Request.QueryString["Medic"]; //strMedic
		if (string.IsNullOrEmpty(medic))
		{
			//TODO: handle medic selection
			/*/
			SQL = SQL & " AND ("
			' pacient case
			SQL = SQL & "(ExternalType = 'PA' AND RequestorID=" & strMedic & ") "
			' presentation case
			SQL = SQL & "OR ((ExternalType = 'P' OR ExternalType = 'P') AND EXISTS "
			SQL = SQL & "(select * from vPresentationFull where ID=vRequestClass.ExternalID AND MedicID=" & strMedic &")) "
			' checkin case
			SQL = SQL & "OR (ExternalType = 'CI' AND EXISTS "
			SQL = SQL & "(select * from vCheckInFull where CIID=vRequestClass.ExternalID AND CIMedicID=" & strMedic &")) "
			' checkup case
			SQL = SQL & "OR (ExternalType = 'CU' AND EXISTS "
			SQL = SQL & "(select * from vCheckUpFull where CUID=vRequestClass.ExternalID AND CUMedic=" & strMedic &")) "
			' checkout case
			SQL = SQL & "OR (ExternalType = 'CO' AND EXISTS "
			SQL = SQL & "(select * from vCheckOutFull where COID=vRequestClass.ExternalID AND COMedicID=" & strMedic &")) "
			SQL = SQL & ") "
			 //*/
		}
		string result = "select distinct RequestID from vRequestClass where 1=1 ";
		if (!string.IsNullOrEmpty(idList))
			result += " AND (" + idList + " 1=0) "; // id=[n] or . (id >= [min] and id <= [max]) or .
		if (!string.IsNullOrEmpty(section))
			result += " AND UPPER(SectionCode)=UPPER('" + section.Replace( "'", "''") + "') ";
		labDomain = Request.QueryString["LabDomains"]; //strClass
		if ((!string.IsNullOrEmpty(labDomain)) && (!labDomain.Equals("*")))
			result += " AND UPPER(Class)=UPPER('" + labDomain.Replace("'", "''") + "') ";
		else
			//if not checkSecLevel(SEC_REPORTS) AND not checkSecLevel(SEC_ADMIN)
//            result += @" AND EXISTS (select * from LAB_DOMAINS where [Domain]=vRequestClass.Class
//										AND Section='" + (Session["Section"] ?? "").ToString().Replace("'", "''") + "') ";
		result += " AND requestedDate BETWEEN '" + startDate + "' AND '" + endDate + @"'
			order by RequestID ";
		return result;
	}
</script>
<script runat="server" id="ProcessRequests">
	private void ProcessRequests(string lister)
	{
		System.Data.DataSet requests = Hipocrate.DB.DBConnection.GetData(lister);
		int nCount = requests.Tables[0].Rows.Count;
		if (nCount == 0)
			Response.Write("Nici o cerere nu a fost gasita conform criteriilor de cautare selectate.");
			//Response.Write "Click <a href='javascript:history.back()'>aici</a> pentru a va intoarce in pagina de cautare."
		else
		{
			string[] parameters = new string[] { "@intCodeID", "@strUserLogin", "@strVisibleClass" };
			for (int r = 0; r < nCount; ++r)
			{
				object reqID = requests.Tables[0].Rows[r]["RequestID"];
				//??? rs.Open @"select *, convert(varchar(20), RequestedDate, 113) as strRequestedDate
				//??? 	from LAB_REQUESTS where [id]=" & intCodeID
				object[] paramValues = new object[] { reqID, Tools.userLogin, null };
				Response.Write(string.Format("[{0}/{1}]Se valideaza cererea numarul {2} ......", r + 1, nCount, reqID));
				if ((!string.IsNullOrEmpty(labDomain)) && (!labDomain.Equals("*")))
					if (!isClassValidated(reqID, labDomain))
					{
						paramValues[2] = labDomain;
						int result = Hipocrate.DB.DBConnection.Execute(procedureName, parameters, paramValues);
						//if err.number > 0 then
						//    Response.Write "<span class='error'>Failed - " & err.Description & "</span>"
						//else
							Response.Write("OK");
					}
					else
						Response.Write("deja validat");
				else
				{
					string sql = "select distinct Class from vAnalyseReport_All where requestID=" + reqID + " order by Class";
					System.Data.DataSet domains = Hipocrate.DB.DBConnection.GetData(sql);
					Response.Write("<table>" + System.Environment.NewLine);
					foreach (System.Data.DataRow d in domains.Tables[0].Rows)
					{
						Response.Write("<tr class='H2'><td width='30 px'></td><td>" + d["Class"] + "</td>");
						Response.Write("<td>......</td>");

						if (!isClassValidated(reqID, d["Class"]))
						{
							paramValues[2] = d["Class"];
							int result = Hipocrate.DB.DBConnection.Execute(procedureName, parameters, paramValues);
							//if err.number > 0 then
							//    Response.Write "<td class='error'>Failed - " & err.Description & "</td>"
							//else
								Response.Write("<td>OK</td>");
						}
						else
							Response.Write("<td>deja validat</td>");
						Response.Write("</tr>");
					}
					Response.Write("</table>" + System.Environment.NewLine);
				}
				Hipocrate.DB.DBConnection.Execute(procedureName, parameters, paramValues);
				Hipocrate.DB.DBConnection.Execute("Lab_Request_SetStatus", new string[] { "@RequestID" }, new object[] { reqID });
				Response.Write("<br>" + System.Environment.NewLine);
				Response.Flush();
			}
			Response.Write("<span class=\"error\">Procesare completa.</span>");
		}
	}
</script>
<script runat="server" id="isClassValidated">
	private bool isClassValidated(object id, object domain)
	{
		string sql = @"select v.RequestID from lab_validated v join lab_domains d on v.DomainID=d.[ID]
			where v.RequestID=" + id + " AND UPPER(d.[Domain])=Upper('" + domain.ToString().Replace("'", "''") + "')";
		System.Data.DataSet result = Hipocrate.DB.DBConnection.GetData(sql);
		//return result.Tables[0].Rows.Count > 0;
		return true;
	}
</script>
<script runat="server" id="TestResponseFlush">
	protected void TestResponseFlush()
	{
		Hipocrate.DB.DBConnection.VariableConnectionString = //"Data Source=localhost;Initial Catalog=test";
			/**/"Data Source=localhost;Initial Catalog=test;User ID=rsc;Password=2010";
		string start = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
		for (int i = 0; i < 10; ++i)
			try
			{
				System.Random rand = new Random();
				int test = rand.Next(0);
				Response.Write("R[0] generated: " + test.ToString() + "<br/><br/>");
				Response.Write("R[2] generated: " + rand.Next(2).ToString() + "<br/><br/>");
				int numberOfLines = 6 + rand.Next(5);
				for (int x = 0; x < numberOfLines; ++x)
					Response.Write(string.Format("Batch #{0}, line {1}<br/>{2}", i + 1, x + 1, System.Environment.NewLine));
				Response.Write("<br/>" + scroller + System.Environment.NewLine);
				Hipocrate.DB.DBConnection.ExecuteVariable(string.Format("insert into tracer(runat, counter) values('{0}', {1})", start, i));
				System.Threading.Thread.Sleep(1000);
				Response.Flush();
			}
			catch (System.Data.SqlClient.SqlException ex)
			{
				Response.Write("<br/> SQL Error: " + ex.ToString() + System.Environment.NewLine);
			}
			catch (Exception ex)
			{
				Response.Write("<br/> Error: " + ex.ToString() + System.Environment.NewLine);
			}
		Response.Write("The End." + scroller);
	}
	private string scroller = @"<script>
			document.body.scrollTop = 99999; window.scrollTo(0, 99999);
		<" + "/script>";
</script>

</html>
